/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import isArray from 'lodash/isArray';

export default function formatAddressData(label: string[][], value: string[][]) {
  const list: any = [];

  if (isArray(label)) {
    value.forEach((item, i) => {
      if (!isArray(item)) return;
      const [pc, cc, dc, sc] = item;
      const [pn, cn, dn, sn] = label[i];
      const p: any = { label: pn, value: pc };
      const c: any = { label: cn, value: cc };
      const d: any = { label: dn, value: dc };
      const s: any = { label: sn, value: sc };
      const pi = list.findIndex((pl: any) => pl.value === p.value);
      if (pi < 0) {
        if (s.label) d.children = [s];
        if (d.label) c.children = [d];
        if (c.label) p.children = [c];
        list.push(p);
      } else {
        const ci = list[pi].children.findIndex((cl: any) => cl.value === c.value);
        if (ci < 0) {
          if (s.label) d.children = [s];
          if (d.label) c.children = [d];
          list[pi].children.push(c);
        } else {
          const di = list[pi].children[ci].children.findIndex((dl: any) => dl.value === d.value);
          if (di < 0) {
            if (s.label) d.children = [s];
            list[pi].children[ci].children.push(d);
          } else {
            const si = list[pi].children[ci].children.findIndex((dl: any) => dl.value === d.value);
            if (si < 0) {
              list[pi].children[ci].children[di].children.push(s);
            }
          }
        }
      }
    });
  }

  return list;
}
